﻿// --------------------------------------------------------------------------------------------------------------------
// <copyright file="Reflection.cs" company="Mir Software">
//   Copyright 2013 Mir Software. All rights reserved.
// </copyright>
// <summary>
//   Defines the Reflection type.
// </summary>
// --------------------------------------------------------------------------------------------------------------------

using System.Collections.Generic;

namespace Yacf
{
    using System;
    using System.Linq;
    using System.Reflection;

    public class Reflection
    {
        private object currentFieldSet;

        /// <summary>
        /// The get config properties from type.
        /// Later on perhaps also fields (var fields = t.GetFields();)
        /// </summary>
        /// <returns>
        /// The <see cref="Dictionary"/>.
        /// </returns>
        internal Dictionary<string, string> GetConfigPropertiesFromType()
        {
            if (this.currentFieldSet == null)
            {
                return new Dictionary<string, string>();
            }

            var t = this.currentFieldSet.GetType();
            var props = t.GetProperties(); 
            var dict = new Dictionary<string, string>();
            foreach (var property in props)
            {
                var value = property.GetValue(this.currentFieldSet);
                ConfigAttributes.ConfigInfo configAttributes = property.GetCustomAttributes<ConfigAttributes.ConfigInfo>(true).FirstOrDefault();

                // var propertyConfigInfo = GetConfigInfo(property);
                dict.Add(property.Name, configAttributes.ConfigKeyPath);
            }

            return dict;
        }

        internal object SetConfig(Dictionary<string, string> userConfig, Yacf yacf)
        {
            var t = this.currentFieldSet.GetType();

            foreach (var uc in userConfig)
            {
                var property = t.GetProperty(uc.Key);
                var currentValue = property.GetValue(this.currentFieldSet);
                var newValue = yacf.GetKeyValue(uc.Value);
                property.SetValue(currentFieldSet, newValue);
            }

            return currentFieldSet;
        }

        public Reflection(object fieldSet)
        {
            this.currentFieldSet = fieldSet;
        }
    }
}
